<template>
  <!-- 所属区域 -->
  <!-- 也可以查询其他的，只需要修改payload -->
  <div>
    {{ regionText }}

    <el-popover placement="top-start" title="选择区域" trigger="hover">
      <el-button type="text" slot="reference" size="small">请选择</el-button>

      <el-cascader-panel
        style="width: 100%"
        ref="cascader"
        :options="options"
        :props="{
          children: 'subRegionList',
          label: 'regionName',
          value: 'regionId',
          lazy: true,
          lazyLoad(node, resolve) {
            const { level, data } = node;

            const getTree = (data) => {
              if (level != 0) {
                api
                  .queryRegionTree({
                    parentId: data.regionId,
                  })
                  .then(({ returnObj }) => {
                    resolve(returnObj);
                  });
              }
            };

            getTree(data);
          },
        }"
        @change="handleChange"
        clearable
      >
      </el-cascader-panel>
    </el-popover>
  </div>
</template>

<script>
import utils from "@/utils";
import { queryRegionTree } from "@/api/common";

export default {
  props: {
    value: {
      required: true,
    },
    regionName: {
      type: String,
    },
  },
  data() {
    return {
      regionText: this.regionName,
      selectvalue: '',
      options: [],
      api: {
        queryRegionTree,
      },
    };
  },
  watch: {
    value(newValue, oldValue) {
      // console.log(newValue);
      this.selectvalue = '';
    },
    regionName(newValue, oldValue) {
      this.regionText = newValue;
    },
  },
  mounted() {
    this.queryData();
  },
  methods: {
    async queryData() {
      try {
        let res = await queryRegionTree({
          parentId: "-1",
        });
        this.options = res.returnObj;
      } catch (error) {
        console.log(error);
      }
    },
    handleChange(val) {
      let currentLbels = this.$refs.cascader.getCheckedNodes()[0].pathLabels;
      this.regionText = currentLbels.join('/')

      let lastVal = val[val.length - 1];
      this.selectvalue = lastVal;
      // 取最后一个
      this.$emit("input", lastVal);
    },
  },
};
</script>

<style lang="scss" scoped></style>
